package com.yangxk.kadmin.web.module.sample.service.impl;

import com.yangxk.kadmin.common.base.AbstractService;
import com.yangxk.kadmin.common.support.generator.IdGenerator;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.common.exception.ParamException;
import com.yangxk.kadmin.web.common.enumeration.ResponseCode;
import com.yangxk.kadmin.web.module.sample.form.CategoryEditForm;
import com.yangxk.kadmin.web.module.sample.form.CategoryQueryForm;
import com.yangxk.kadmin.web.module.sample.mapper.CategoryMapper;
import com.yangxk.kadmin.web.module.sample.po.Category;
import com.yangxk.kadmin.web.module.sample.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yangxk.kadmin.common.support.BeanValidator;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl extends AbstractService<Category, Long> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> queryAll() {
        return categoryMapper.queryAll();
    }

    @Override
    public PageInfo<Category> queryByPage(CategoryQueryForm categoryQueryForm) {

        PageHelper.startPage(categoryQueryForm.getPageNum(), categoryQueryForm.getPageSize());

        List<Category> categoryList = categoryMapper.selectList(categoryQueryForm);

        return new PageInfo<>(categoryList);
    }

    @Transactional
    @Override
    public long addCategory(CategoryEditForm form) {
        BeanValidator.check(form);
        Category category = new Category();
        BeanUtils.copyProperties(form, category);

        category.setId(IdGenerator.getId());
        // TODO 设置创建 更新时间
        categoryMapper.insertSelective(category);

        return category.getId();
    }

    @Override
    @Transactional
    public long updateCategory(CategoryEditForm updateForm) {
        BeanValidator.check(updateForm);

        if (updateForm.getId() == null)
            throw new ParamException("id不能为空");

        Category category = categoryMapper.selectByPrimaryKey(updateForm.getId());
        if (category == null)
            throw new BizException(ResponseCode.UPDATE_CHECK_NULL);

        Category update = new Category();
        BeanUtils.copyProperties(updateForm, update);
        // TODO 设置更新时间

        categoryMapper.updateByPrimaryKeySelective(update);
        return category.getId();
    }

    @Override
    @Transactional
    public void deleteCategory(long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category == null)
            throw new BizException(ResponseCode.UPDATE_CHECK_NULL);

        categoryMapper.deleteByPrimaryKey(id);
    }
}
